/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.music2;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.music2.R;

public class CreateFolder extends Activity
{
    private EditText mPlaylist;
    private TextView mPrompt;
    private Button mSaveButton;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.create_playlist);
        getWindow().setLayout(WindowManager.LayoutParams.FILL_PARENT,
                                    WindowManager.LayoutParams.WRAP_CONTENT);

        mPrompt = (TextView)findViewById(R.id.prompt);
        mPlaylist = (EditText)findViewById(R.id.playlist);
        mSaveButton = (Button) findViewById(R.id.create);
        mSaveButton.setOnClickListener(mOpenClicked);
        mSaveButton.setText(R.string.create_playlist_create_text);

        ((Button)findViewById(R.id.cancel)).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });
        
        String defaultname = icicle != null ? icicle.getString("defaultname") : makeSuggestedFolderName();
        if (defaultname == null) {
            finish();
            return;
        }
        //String promptformat = getString(R.string.create_playlist_create_text_prompt);
        //String prompt = String.format(promptformat, defaultname);
        mPrompt.setText("Create Playlist Folder");
        mPlaylist.setText(defaultname);
        mPlaylist.setSelection(defaultname.length());
    }
    

    
    private int idForFolder(String name) {
        Cursor c = MusicUtils.query(this, ExtendedAudioProvider.CONTENT_URI_FOLDERS,
                new String[] { ExtendedAudioProvider._ID },
                ExtendedAudioProvider.FOLDER_NAME + "=?",
                new String[] { name },
                ExtendedAudioProvider.FOLDER_NAME);
        int id = -1;
        if (c != null) {
            c.moveToFirst();
            if (!c.isAfterLast()) {
                id = c.getInt(0);
            }
        }
        c.close();
        return id;
    }
    
    @Override
    public void onSaveInstanceState(Bundle outcicle) {
        outcicle.putString("defaultname", mPlaylist.getText().toString());
    }
    
    @Override
    public void onResume() {
        super.onResume();
    }

    private String makeSuggestedFolderName() {

        String template = getString(R.string.new_folder_name_template);
        int num = 1;

        String[] cols = new String[] {
                MediaStore.Audio.Playlists.NAME
        };
        ContentResolver resolver = getContentResolver();
        String whereclause = ExtendedAudioProvider.FOLDER_NAME + " != ''";
        Cursor c = resolver.query(ExtendedAudioProvider.CONTENT_URI_FOLDERS,
            cols, whereclause, null,
            ExtendedAudioProvider.FOLDER_NAME);

        if (c == null) {
            return null;
        }
        
        String suggestedname;
        suggestedname = String.format(template, num++);
        
        // Need to loop until we've made 1 full pass through without finding a match.
        // Looping more than once shouldn't happen very often, but will happen if
        // you have folders named "New Folder 1"/10/2/3/4/5/6/7/8/9, where
        // making only one pass would result in "New Folder 10" being erroneously
        // picked for the new name.
        boolean done = false;
        while (!done) {
            done = true;
            c.moveToFirst();
            while (! c.isAfterLast()) {
                String playlistname = c.getString(0);
                if (playlistname.compareToIgnoreCase(suggestedname) == 0) {
                    suggestedname = String.format(template, num++);
                    done = false;
                }
                c.moveToNext();
            }
        }
        c.close();
        return suggestedname;
    }
    
    private View.OnClickListener mOpenClicked = new View.OnClickListener() {
        public void onClick(View v) {
            String name = mPlaylist.getText().toString();
            if (name != null && name.length() > 0) {
                ContentResolver resolver = getContentResolver();
                int id = idForFolder(name);
                Uri uri;
                if (id >= 0) {
                	Toast.makeText(getApplicationContext(), "Folder already exists", Toast.LENGTH_SHORT).show();
                } else {
                	//create new folder
                    ContentValues values = new ContentValues(1);
                    values.put(ExtendedAudioProvider.FOLDER_NAME, name); 
                    uri = resolver.insert(ExtendedAudioProvider.CONTENT_URI_FOLDERS, values);
                    
                    setResult(RESULT_OK, (new Intent()).setData(uri));
                    finish();
                }

            }
        }
    };
}
